import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { memoryApi } from '@/api/memory'

export const useMemoryStore = defineStore('memory', () => {
  // 状态
  const loading = ref(false)
  const processes = ref([])
  const objects = ref([])
  const memoryStats = ref({})
  const error = ref('')

  // 分页和筛选
  const currentPage = ref(1)
  const pageSize = ref(20)
  const filters = ref({
    search: '',
    category: '',
    sortBy: 'Rss',
    sortOrder: 'desc'
  })

  // 计算属性
  const total = computed(() => processes.value.length)

  const filteredProcesses = computed(() => {
    let result = [...processes.value]

    // 搜索筛选
    if (filters.value.search) {
      const searchTerm = filters.value.search.toLowerCase()
      result = result.filter(process =>
        process.name?.toLowerCase().includes(searchTerm) ||
        process.process?.toLowerCase().includes(searchTerm) ||
        process.pid?.toString().includes(searchTerm)
      )
    }

    // 分类筛选
    if (filters.value.category) {
      result = result.filter(process => process.category === filters.value.category)
    }

    // 排序
    if (filters.value.sortBy) {
      result.sort((a, b) => {
        const aValue = parseFloat(a[filters.value.sortBy]) || 0
        const bValue = parseFloat(b[filters.value.sortBy]) || 0

        if (filters.value.sortOrder === 'asc') {
          return aValue - bValue
        } else {
          return bValue - aValue
        }
      })
    }

    return result
  })

  const paginatedProcesses = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return filteredProcesses.value.slice(start, end)
  })

  const totalMemoryUsage = computed(() => {
    return processes.value.reduce((total, process) => {
      return total + (parseFloat(process.Rss) || 0)
    }, 0)
  })

  const memoryStatsSummary = computed(() => {
    const rssTotal = processes.value.reduce((sum, p) => sum + (parseFloat(p.Rss) || 0), 0)
    const pssTotal = processes.value.reduce((sum, p) => sum + (parseFloat(p.Pss) || 0), 0)
    const sharedCleanTotal = processes.value.reduce((sum, p) => sum + (parseFloat(p.Shared_Clean) || 0), 0)
    const sharedDirtyTotal = processes.value.reduce((sum, p) => sum + (parseFloat(p.Shared_Dirty) || 0), 0)
    const privateCleanTotal = processes.value.reduce((sum, p) => sum + (parseFloat(p.Private_Clean) || 0), 0)
    const privateDirtyTotal = processes.value.reduce((sum, p) => sum + (parseFloat(p.Private_Dirty) || 0), 0)

    return {
      rssTotal,
      pssTotal,
      sharedCleanTotal,
      sharedDirtyTotal,
      privateCleanTotal,
      privateDirtyTotal,
      processCount: processes.value.length
    }
  })

  // 方法
  const fetchProcesses = async (productName, version) => {
    if (!productName) {
      error.value = '请先选择产品版本'
      return
    }

    loading.value = true
    error.value = ''

    try {
      const response = await memoryApi.getProcesses(productName, version)
      processes.value = response.data || []
    } catch (err) {
      console.error('获取进程内存信息失败:', err)
      error.value = '获取进程内存信息失败，请重试'
      processes.value = []
    } finally {
      loading.value = false
    }
  }

  const fetchObjects = async (productName, version) => {
    if (!productName) {
      error.value = '请先选择产品版本'
      return
    }

    loading.value = true
    error.value = ''

    try {
      const response = await memoryApi.getObjects(productName, version)
      objects.value = response.data || []
    } catch (err) {
      console.error('获取对象内存信息失败:', err)
      error.value = '获取对象内存信息失败，请重试'
      objects.value = []
    } finally {
      loading.value = false
    }
  }

  const fetchMemoryStats = async (productName, version) => {
    if (!productName) {
      error.value = '请先选择产品版本'
      return
    }

    try {
      const response = await memoryApi.getMemoryStats(productName, version)
      memoryStats.value = response.data || {}
    } catch (err) {
      console.error('获取内存统计信息失败:', err)
      error.value = '获取内存统计信息失败，请重试'
      memoryStats.value = {}
    }
  }

  const setFilters = (newFilters) => {
    filters.value = { ...filters.value, ...newFilters }
    currentPage.value = 1 // 重置到第一页
  }

  const clearFilters = () => {
    filters.value = {
      search: '',
      category: '',
      sortBy: 'Rss',
      sortOrder: 'desc'
    }
    currentPage.value = 1
  }

  const setCurrentPage = (page) => {
    currentPage.value = page
  }

  const setPageSize = (size) => {
    pageSize.value = size
    currentPage.value = 1
  }

  const formatBytes = (bytes) => {
    if (!bytes || bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  const exportProcesses = (format = 'csv') => {
    const headers = ['PID', '进程名', '类别', '线程数', '对象数', 'VMA数', 'RSS', 'PSS', '共享干净页', '共享脏页', '私有干净页', '私有脏页']
    const rows = filteredProcesses.value.map(process => [
      process.pid || '',
      process.process || process.name || '',
      process.category || '',
      process.threads || 0,
      process.objects || 0,
      process.vmas || 0,
      formatBytes(process.Rss || 0),
      formatBytes(process.Pss || 0),
      formatBytes(process.Shared_Clean || 0),
      formatBytes(process.Shared_Dirty || 0),
      formatBytes(process.Private_Clean || 0),
      formatBytes(process.Private_Dirty || 0)
    ])

    if (format === 'csv') {
      const csvContent = [
        headers.join(','),
        ...rows.map(row => row.map(cell => `"${cell}"`).join(','))
      ].join('\n')

      return new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    }

    return null
  }

  // 重置状态
  const reset = () => {
    processes.value = []
    objects.value = []
    memoryStats.value = {}
    loading.value = false
    error.value = ''
    currentPage.value = 1
    filters.value = {
      search: '',
      category: '',
      sortBy: 'Rss',
      sortOrder: 'desc'
    }
  }

  return {
    // 状态
    loading,
    processes,
    objects,
    memoryStats,
    error,
    currentPage,
    pageSize,
    filters,

    // 计算属性
    total,
    filteredProcesses,
    paginatedProcesses,
    totalMemoryUsage,
    memoryStatsSummary,

    // 方法
    fetchProcesses,
    fetchObjects,
    fetchMemoryStats,
    setFilters,
    clearFilters,
    setCurrentPage,
    setPageSize,
    formatBytes,
    exportProcesses,
    reset
  }
})